<?php

/**
 * Zeed Platform Project
 * Based on Zeed Framework & Zend Framework.
 * 
 * LICENSE
 * http://www.zeed.com.cn/license/
 * 
 * @category   Zeed
 * @package    Zeed_ChangeMe
 * @subpackage ChangeMe
 * @copyright  Copyright (c) 2010 Zeed Technologies PRC Inc. (http://www.zeed.com.cn)
 * @author     Zeed Team (http://blog.zeed.com.cn)
 * @since      2011-3-21
 * @version    SVN: $Id$
 */
class NotifyController extends TrendAdminAbstract
{
    public $perpage = 15;
    
    /**
     * 通知信息列表
     */
    public function index ()
    {
        $this->addResult(self::RS_SUCCESS, 'json');
        
        /* 接收参数 */
        $ordername = $this->input->get('ordername', null);
        $orderby = $this->input->get('orderby', null);
        $page = (int) $this->input->get('pageIndex', 0);
        $perpage = $this->input->get('pageSize', $this->perpage);
        $time_start = $this->input->get('ctime_start');
        $time_end = $this->input->get('ctime_end');
        
        /* ajax 加载数据 */
        if ($this->input->isAJAX()) {
            $offset = $page * $perpage;
            $page = $page + 1;
            
            $where = array(
                    'to_userid' => (int) $this->_userid,
                    'is_del' => 0
            );
            if ($time_start && $time_end) {
                $where['$and'] = [
                        ['ctime'=>
                                ['$gte' => strtotime($time_start) * 1000] // new MongoDate()
                        ],
                        ['ctime'=>
                                ['$lte' =>  (strtotime($time_end) + 24 * 3600 - 1) * 1000]
                        ]
                ];
            } else {
                if ($time_start) {
                    $startime = strtotime($time_start) * 1000; // new MongoDate(strtotime($time_start));
                    $where['ctime'] = ['$gte' => $startime];
                }
                
                if ($time_end) {
                    $endtime = (strtotime($time_end) + 24 * 3600 - 1) * 1000;
                    $where['ctime'] = ['$lte' => $endtime];
                }
            }
            
            $order = array('ctime' => 'DESC');
            
            $content = Trend_Model_Notify::instance()->fetchByWhere($where, $order, $perpage, $offset);
            $data['count'] = Trend_Model_Notify::instance()->getCount($where);
            
            /* 处理其他一些信息 */
            if (! empty($content)) {
                /* 解析通知详情 */
                foreach ($content as $k => &$v) {
                    /* 格式化时间 */
                    if (strlen($v['ctime']) == 13) {
                        $v['ctime'] = Util_Timer::formatMicrotime($v['ctime']);
                    } else {
                        $v['ctime'] = date(DATETIME_FORMAT, $v['ctime']);
                    }
                    
                    /* 处理申请人 */
                    $user_info = Admin_Model_User::instance()->fetchByPK($v['send_userid'], array('fullname'));
                    $v['send_user_fullname'] = $user_info[0]['fullname'];
                    
                    /* 解析扩展内容 */
                    $v['extra'] = json_decode($v['extra'], true);
                    
                    /* 处理案件名称及编号 */
                    if ($v['type'] == 'card_delete_confirm') {
                        $archive_info = Archive_Model_Content::instance()->fetchByFV('sn', $v['extra']['card_info']['sn']);
                        $v['extra']['archive_info']['title'] = $archive_info[0]['title'];
                        $v['extra']['archive_info']['sn'] = $archive_info[0]['sn'];
                    }
                    
                    /* 处理状态 */
                    $confirm_info = Archive_Model_Confirm::instance()->fetchByPK($v['extra']['confirm_info']['_id']);
                    $v['extra']['confirm_info'] = ! empty($confirm_info) ? $confirm_info[0] : array();
                }
            }
            
            $data['content'] = $content ? $content : array();
        }
        
        $data['ordername'] = $ordername;
        $data['orderby'] = $orderby;
        $data['page'] = $page;
        $data['perpage'] = $perpage;
        
        $this->setData('data', $data);
        $this->addResult(self::RS_SUCCESS, 'php', 'notify.index');
        return parent::multipleResult(self::RS_SUCCESS);
    }
    
    /**
     * 通知信息详情
     */
    public function detail()
    {
        $this->addResult(self::RS_SUCCESS, 'json');
        
        /* 接收参数 */
        $_id = $this->input->get('_id');
        
        /* 查询详情 */
        $content = Trend_Model_Notify::instance()->fetchByPK($_id);
        if (empty($content)) {
            exit('查无此通知信息');
        }
        $content = $content[0];
        
        /* 格式化时间 */
        if (strlen($content['ctime']) == 13) {
            $content['ctime'] = Util_Timer::formatMicrotime($content['ctime']);
        } else {
            $content['ctime'] = date(DATETIME_FORMAT, $content['ctime']);
        }
        
        if (strlen($content['mtime']) == 13) {
            $content['mtime'] = Util_Timer::formatMicrotime($content['mtime']);
        } else {
            $content['mtime'] = date(DATETIME_FORMAT, $content['mtime']);
        }
        
        /* 处理申请人 */
        $user_info = Admin_Model_User::instance()->fetchByPK($content['send_userid'], array('fullname'));
        $content['send_user_fullname'] = $user_info[0]['fullname'];
        
        /* 处理通知扩展信息内容 */
        $content['extra_arr'] = json_decode($content['extra'], true);
        $archive_info = isset($content['extra_arr']['archive_info']) ? $content['extra_arr']['archive_info'] : array();
        $card_info = isset($content['extra_arr']['card_info']) ? $content['extra_arr']['card_info'] : array();
        $attachment_info = isset($content['extra_arr']['attachment_info']) ? $content['extra_arr']['attachment_info'] : array();
        $confirm_info = isset($content['extra_arr']['confirm_info']) ? $content['extra_arr']['confirm_info'] : array();
        
        /* 获取最新的二次确认消息 */
        $confirm_info = Archive_Model_Confirm::instance()->fetchByPK($confirm_info['_id']);
        $confirm_info = ! empty($confirm_info) ? $confirm_info[0] : array();
        
        /* 根据类型做区别处理 */
        $content['status'] = 0;
        if ($content['type'] == 'archive_delete_confirm') {
            /* 处理模板 */
            $template = 'notify.detail.archive.html';
        } elseif ($content['type'] == 'card_delete_confirm') {
            /* 获取相关案件信息 */
            $archive_info = Archive_Model_Content::instance()->fetchByFV('sn', $card_info['sn']);
            $archive_info = ! empty($archive_info) ? $archive_info[0] : array();
            
            /* 处理模板 */
            $template = 'notify.detail.card.html';
        } elseif ($content['type'] == 'attachment_delete_confirm') {
            /* 获取行动相关信息 */
            $card_info_rel_a = Archive_Model_Card::instance()->fetchByPK($content['extra_arr']['card_id']);
            $card_info = ! empty($card_info_rel_a) ? $card_info_rel_a[0] : array();

            /* 获取相关案件信息 */
            $archive_info = Archive_Model_Content::instance()->fetchByFV('sn', $card_info['sn']);
            $archive_info = ! empty($archive_info) ? $archive_info[0] : array();
            
            /* 处理模板 */
            $template = 'notify.detail.attachment.html';
        } else {
            /* 处理模板 */
            $template = 'notify.detail.html';
        }
        
        /* 标记为已读 */
        $set_notify = array(
                'read_users' => ':' . $this->_userid . ':',
                'mtime' => Util_Timer::getMicrotime()
        );
        Trend_Model_Notify::instance()->updateForEntity($set_notify, $_id);
        
        /* 剔除多余元素 */
        unset($content['extra_arr']);
        
        /* 组织返回数据 */
        $data = array(
                'content' => ! empty($content) ? $content : array(),
                'archive_info' => $archive_info,
                'card_info' => $card_info,
                'attachment_info' => $attachment_info,
                'confirm_info' => $confirm_info,
                'template' => $template
        );
        
        $this->setData('data', $data);
        $this->addResult(self::RS_SUCCESS, 'php', 'notify.detail');
        return parent::multipleResult(self::RS_SUCCESS);
    }
    
    /**
     * 标记为已读 - 单条
     */
    public function settingReadSingle()
    {
        $this->addResult(self::RS_SUCCESS, 'json');
        
        /* 接收参数 */
        $id = $this->input->query('id');
        
        try {
            /* 检查请求方式 */
            if (! $this->input->isAJAX()) {
                throw new Zeed_Exception('请求方式错误');
            }
            
            /* 检查请求参数 */
            if (! $id) {
                throw new Zeed_Exception('缺少参数，或参数错误');
            }
            
            /* 查询详情 */
            $content = Shortvideo_Model_Trend_Notify::instance()->fetchByPK($id);
            if (empty($content)) {
                throw new Zeed_Exception('查无此通知信息');
            }
            $content = $content[0];
            
            /* 标记为已读 */
            if (strpos($content['read_users'], ':' . $this->_userid . ':') === false) {
                if ($content['read_users']) {
                    $set_read_users = array('read_users' => $content['read_users'] . $this->_userid . ':');
                } else {
                    $set_read_users = array('read_users' => ':' . $this->_userid . ':');
                }
                Shortvideo_Model_Trend_Notify::instance()->updateForEntity($set_read_users, $id, $this->_pre_entity);
            }
        } catch (Zeed_Exception $e) {
            $this->setStatus($e->getCode() ? $e->getCode() : 1);
            $this->setError('设置失败 : ' . $e->getMessage());
        }
        
        return self::RS_SUCCESS;
    }
    
    /**
     * 标记为已读 - 全部
     */
    public function settingReadAll()
    {
        $this->addResult(self::RS_SUCCESS, 'json');
        
        try {
            /* 检查请求方式 */
            if (! $this->input->isAJAX()) {
                throw new Zeed_Exception('请求方式错误');
            }
            
            /* 标记为已读 */
            $where_noread = "read_users IS null OR read_users NOT REGEXP ':" . $this->_userid . ":'";
            $notifies = Shortvideo_Model_Trend_Notify::instance()->fetchByWhere($where_noread);
            if (! empty($notifies)) {
                foreach ($notifies as $kk => $vv) {
                    if ($vv['read_users']) {
                        $set_read_users = array('read_users' => $vv['read_users'] . $this->_userid . ':');
                    } else {
                        $set_read_users = array('read_users' => ':' . $this->_userid . ':');
                    }
                    Shortvideo_Model_Trend_Notify::instance()->updateForEntity($set_read_users, $vv['id'], $this->_pre_entity);
                }
            }
        } catch (Zeed_Exception $e) {
            $this->setStatus($e->getCode() ? $e->getCode() : 1);
            $this->setError('设置失败 : ' . $e->getMessage());
        }
        
        return self::RS_SUCCESS;
    }
    
    /**
     * 获取当前登录用户未读的站内消息
     */
    public function getNotifyForNoread ()
    {
        $this->addResult(self::RS_SUCCESS, 'json');
        
        try {
            /* 获取数据 */
            $where = array(
                    'is_del' => 0,
                    'read_users' => '',
                    'to_userid' => $this->_userid
            );
            $order = 'ctime DESC';
            $notifies = Trend_Model_Notify::instance()->fetchByWhere($where, $order);
            
            /* 数据基础处理 */
            if (! empty($notifies)) {
                foreach ($notifies as $k => &$v) {
                    /* 处理时间 */
                    $v['ctime'] = Util_Timer::formatMicrotime($v['ctime'], 'Y-m-d H:i:s');
                }
            }
            
            $data['notifies'] = $notifies;
        } catch (Zeed_Exception $e) {
            $this->setStatus(1);
            $this->setError('获取通知消息失败 : ' . $e->getMessage());
            return self::RS_SUCCESS;
        }
        
        $this->setError('获取通知消息成功');
        $this->setData('data', $data);
        return self::RS_SUCCESS;
    }
}

// End ^ Native EOL ^ UTF-8